package controller;

import java.io.IOException;
import java.util.regex.Matcher;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

public class NewLetterServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String name = req.getParameter("name");
		String email = req.getParameter("email");
		
		if(name!=null&&email!=null)
		{
			java.util.regex.Pattern p = java.util.regex.Pattern.compile(".+@.+\\.[a-z]+");
		    Matcher m = p.matcher(email);
		    boolean matchFound = m.matches();

		    if (!matchFound)
		    {
		    	resp.sendRedirect("/?letter=Invalid Email");
		    } else {
				DBCollection collection = Data.data("email");
				DBObject object = collection.findOne(new BasicDBObject("email",email));
				if(object==null)
				{
					BasicDBObject basicDBObject = new BasicDBObject();
					basicDBObject.put("name", name);
					basicDBObject.put("email", email);
					collection.insert(basicDBObject);
					resp.sendRedirect("/?letter=Register success");
				} else {
					resp.sendRedirect("/?letter=Email already exists");
				}
		    }
		}	
	}
}
